package basic

import (
	"fmt"
	"sort"
	"strings"
)

func Map() {
	//map是一种无序的基于key-value的数据结构，Go语言中的map是引用类型，必须初始化才能使用。
	var a = make(map[string]interface{})
	b := map[string]int{}
	b["aa"] = 111
	if a == nil {
		fmt.Print(111)
	}
	v, ok := b["aa"]
	delete(b, "aa")
	fmt.Print(v, ok)
	fmt.Print(a, b)

	//按指定顺序排序
	d := map[string]int{
		"cc": 4,
		"aa": 1,
		"dd": 3,
		"bb": 2,
	}
	var keys []string
	var values []int
	for k, v := range d {
		keys = append(keys, k)
		values = append(values, v)
	}
	sort.Strings(keys)
	for _, value := range keys {
		fmt.Print(value, d[value])
	}
	sort.Ints(values)
	for _, val := range values {
		for km, kv := range d {
			if val == kv {
				fmt.Print(km, kv)
			}
		}
	}

	computeWordTimes("how do you do")

	test()

}

func computeWordTimes(str string) map[string]int {
	res := make(map[string]int)
	strSlice := strings.Split(str, " ")
	for _, value := range strSlice {
		_, ok := res[value]
		if !ok {
			res[value] = 1
		} else {
			res[value] += 1
		}
	}
	fmt.Print(strSlice, res)
	return res
}

func test() {
	s := []int{1, 2}
	s = append(s, 3)
	fmt.Print(s, len(s), cap(s))
	f := s
	fmt.Print(f, len(f), cap(f))
	s = append(s, 5)
	fmt.Print(s, len(s), cap(s))
	fmt.Print(f, len(f), cap(f))
}
